<template>
  <!-- 主弹框：回撤列表查询 -->
  <el-dialog
    v-model="dialogVisible"
    title="回撤列表查询"
    width="80%"
    :before-close="handleClose"
    draggable
    destroy-on-close
    v-loading="loading"
  >
    <!-- 搜索筛选区域 -->
    <div class="search-wrapper">
      <el-form :model="searchForm" :inline="true" size="default">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入关键词"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operation_type" placeholder="请选择操作类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option
              v-for="option in operationTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-divider />

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="400"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160" align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div class="dialog-footer" style="justify-content: flex-end">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 详情弹框组件（子组件） -->
  <RetreatDetails ref="detailsRef" @confirm="onDetailsConfirm" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { ElMessage } from "element-plus"
import { Search, Refresh } from "@element-plus/icons-vue"
import { getOperationRecordListApi, getOperationTypeOptionsApi } from "@/api/common/index"
import RetreatDetails from "./RetreatDetails.vue"

/** 列表项类型 */
interface ListItem {
  id: number
  title: string
  content: string
  operator_name: string
  ip_address: string
  user_agent: string
  status: number
  create_time: string
  update_time: string
  [key: string]: any
}

/** 搜索表单类型 */
interface SearchForm {
  keyword: string
  operation_type: string
  status: string
  dateRange: any
}

/** 分页类型 */
interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

/** 弹框与表格状态 */
const dialogVisible = ref(false)
const loading = ref(false)
const tableData = ref<ListItem[]>([])
const selectedRows = ref<ListItem[]>([])
const operationTypeOptions = ref<Array<{ label: string; value: string }>>([])

/** 子弹框 ref */
const detailsRef = ref<any>(null)

const onDetailsConfirm = (rows: any[]) => {
  emit("confirm", rows)
}

/** 搜索表单 */
const searchForm = reactive<SearchForm>({
  keyword: "",
  operation_type: "",
  status: "",
  dateRange: null
})

/** 分页数据 */
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

/** 向父级抛出事件，保持兼容 */
const emit = defineEmits(["confirm", "view", "batch-operation", "edit"])

/** 获取操作类型选项 */
const fetchOperationTypeOptions = async () => {
  try {
    const response: any = await getOperationTypeOptionsApi()
    if (response.code === 200 && response.data) {
      operationTypeOptions.value = response.data.map((item: any) => ({
        label: item.label,
        value: item.value
      }))
    } else {
      ElMessage.warning(response.message || "操作类型选项加载失败")
    }
  } catch (error) {
    console.error("获取操作类型选项失败:", error)
    ElMessage.error("操作类型选项加载失败，请重试")
  }
}

/** 获取列表数据 */
const fetchListData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      title: searchForm.keyword || undefined,
      type: "IN",
      start_time: searchForm.dateRange?.[0] || undefined,
      end_time: searchForm.dateRange?.[1] || undefined
    }
    const response: any = await getOperationRecordListApi(params)
    if (response.code === 200) {
      tableData.value = response.data?.list || []
      pagination.total = response.data?.total || 0
    } else {
      ElMessage.error(response.message || "数据加载失败")
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    ElMessage.error("数据加载失败，请重试")
    console.error("API调用失败:", error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

/** 状态相关 */
const getStatusType = (status: number) => {
  return status === 1 ? "success" : "danger"
}
const getStatusText = (status: number) => {
  return status === 1 ? "成功" : "失败"
}

/** 搜索与重置 */
const handleSearch = () => {
  pagination.currentPage = 1
  fetchListData()
}
const handleReset = () => {
  searchForm.keyword = ""
  searchForm.operation_type = ""
  searchForm.status = ""
  searchForm.dateRange = null
  pagination.currentPage = 1
  fetchListData()
}

/** 分页变化 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchListData()
}
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchListData()
}

/** 表格选择与点击 */
const handleSelectionChange = (selection: ListItem[]) => {
  selectedRows.value = selection
}
const handleRowClick = (row: ListItem, column: any) => {
  if (column.type === "selection") return
}

/** 查看：打开详情组件 */
const handleView = (row: ListItem) => {
  emit("view", row)
  if (detailsRef.value?.open) {
    detailsRef.value.open(row)
  }
}

/** 主弹框关闭 */
const handleClose = () => {
  dialogVisible.value = false
  selectedRows.value = []
  searchForm.keyword = ""
  searchForm.operation_type = ""
  searchForm.status = ""
  searchForm.dateRange = null
  pagination.currentPage = 1
}

/** 对外暴露：打开主弹框 */
const openDialog = () => {
  dialogVisible.value = true
  fetchOperationTypeOptions()
  fetchListData()
}
defineExpose({
  openDialog
})

/** 挂载时可做初始化 */
onMounted(() => {})
</script>

<style scoped lang="scss">
.search-wrapper {
  margin-bottom: 16px;
  .el-form {
    margin-bottom: 0;
  }
}
.table-wrapper {
  margin-bottom: 16px;
}
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .footer-left {
    flex: 1;
  }
  .footer-right {
    display: flex;
    gap: 8px;
  }
}
:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
    font-weight: 500;
  }
}
:deep(.el-form--inline) {
  .el-form-item {
    margin-bottom: 12px;
  }
}
@media (max-width: 768px) {
  .search-wrapper {
    :deep(.el-form--inline) {
      .el-form-item {
        display: block;
        margin-right: 0;
      }
    }
  }
  .dialog-footer {
    flex-direction: column;
    gap: 12px;
    .footer-left,
    .footer-right {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>
